package com.xzc.jcip._4_.对象的组合.安全委托;

import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl;
import net.jcip.annotations.ThreadSafe;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CM=UM<>newMap
 **/
@ThreadSafe
public class DelegatingVehicleTracker {
    private final ConcurrentHashMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(Map<String, Point> points) {
        locations = new ConcurrentHashMap<>(points);
        //因为这里包装的是locations，也就是他们指向的同一个map，所以当下面setLocation改变了，它也会改变
        unmodifiableMap = Collections.unmodifiableMap(locations);
    }

    //如果这里是MutablePoint那么就不是线程安全，因为MP可以改变
    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(String id) {
        return locations.get(id);
    }

    public void setLocation(String id, int x, int y) {
        if (locations.replace(id, new Point(x, y)) == null) {
            throw new IllegalArgumentException("invalid vehicle name: " + id);
        }
    }

    public Map<String, Point> getLocationsStatic() {
        //这里因为用的是另外一个实例，已经不是locations了，所以setLocation改变了，这里是不知道的
        return Collections.unmodifiableMap(new HashMap<>(locations));
    }

    public static void main(String[] args) {
        Point p1 = new Point(1, 1);
        Map<String, Point> map1 = new HashMap<>();
        map1.put("1", p1);
        DelegatingVehicleTracker d1 = new DelegatingVehicleTracker(map1);
        Map<String, Point> mapU1 = d1.getLocations();
        Map<String, Point> mapUS1 = d1.getLocationsStatic();
        d1.setLocation("1", 2, 2);
    }
}
